package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void saveOrUpdate(Role role,Long[] permissionIds) {
        if (role.getId()!=null){
            // id不为空,说明此时调用的是修改操作
            // Update 表名 set name=?,sn=? where id=?;
            roleMapper.updateByPrimaryKey(role);
            roleMapper.deleteRoleAndPermissionRelation(role.getId());
        }else {
            // id为空,说明此时调用的是保存操作
            // insert into 表名(name,sn) values(?,?)
            roleMapper.insert(role);
        }
        if(permissionIds!=null){
            for(Long permissionId:permissionIds){
                roleMapper.insertRoleAndPermissionRelation(role.getId(),permissionId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRoleAndPermissionRelation(id);
    }

    @Override
    public Role getOne(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> listAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    @Override
    public PageResult query(QueryObject qo) {
        //查询总条数
        int totalCount = roleMapper.queryForCount();
        //查询带有分页效果的结果集
        if (totalCount == 0){
            //查不出数据,调用的是pageResult类中的缺参构造器
            return new PageResult(qo.getCurrentPage(),qo.getPageSize());
        }

        List<Role> data = roleMapper.queryForList(qo);
        return new PageResult(data,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }
}
